<script setup>
import { ref, onMounted } from 'vue'
import easyapi from '../api'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import { Download } from '@element-plus/icons-vue'
// 定义绑定的数据
const tableData = ref([])
const addWinVisible = ref(false)
const editWinVisible = ref(false)
const addObject = ref({})
const editObject = ref({})
let editIndex = -1
const checkObj = ref({ page: 1, size: 5 })
const total = ref(90)

// 挂载页面时查询数据
onMounted(async function () {
  await checkDate();
  await getAllGuestsData();
})

// 删除操作
const del = async function (index, row) {
  await ElMessageBox.confirm(
    '确定要删除该行数据吗？',
    '提示框',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async function () {
    // 提交数据
    let result = await easyapi.del('/api/guests', row.id)
    // 刷新表单数据
    tableData.value.splice(index, 1)
    if (result.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    } else {
      ElMessage({
        type: 'info',
        message: result.message
      })
    }
  })
}

// 显示新增窗口
const openAddWin = () => {
  addObject.value = {}
  addWinVisible.value = true
}

// 关闭新增窗口
const closeAddWin = () => {
  addWinVisible.value = false
}

// 保存新增数据
const addSave = async function () {
  let result = await easyapi.postJson('/api/guestsjson', addObject.value)
  // 表格数据变更
  tableData.value.unshift(result.data)
  ElMessage({
    type: 'success',
    message: '保存成功'
  })
  closeAddWin()
}

// 点击编辑按钮执行的方法
const edit = function (index, row) {
  // 记录数该数据的下标
  editIndex = index
  // 绑定要修改的数据
  editObject.value.id = row.id
  editObject.value.name = row.name
  editObject.value.phone_number = row.phone_number
  editObject.value.id_number = row.id_number
  editObject.value.number = row.number
  editObject.value.check_in_date = row.check_in_date
  editObject.value.check_out_date = row.check_out_date
  // 打开对话框
  editWinVisible.value = true
}

// 保存修改编辑数据
const editSave = async function () {
  let result = await easyapi.putJson('/api/guestsjson', editObject.value)
  // 刷新表格
  tableData.value[editIndex] = result.data
  // 提示
  ElMessage({
    type: 'success',
    message: '保存成功'
  })
  editWinVisible.value = false
}

// 查询数据
const checkDate = async function (val) {
  if (typeof val === 'number') {
    checkObj.value.page = val
  }
  let result = await easyapi.getSearch('/api/searchguests', checkObj.value)
  tableData.value = result.data.list
  total.value = result.data.count
}
/**************************************************** */
const allGuestsData = ref([]);

// 获取所有数据的函数
const getAllGuestsData = async function() {
  let currentPage = 1;
  let hasMoreData = true;

  while (hasMoreData) {
    checkObj.value.page = currentPage;
    let result = await easyapi.getSearch("/api/searchguests", checkObj.value);

    if (result.data && result.data.list.length > 0) {
      allGuestsData.value.push(...result.data.list);
      currentPage++;
    } else {
      hasMoreData = false;
    }
  }
};
const exportButtonLoading=ref(false);

// 导出表格数据到 Excel 文件
const exportTableToExcel = async () => {
  exportButtonLoading.value = true;

  try {
    // 如果还没有获取所有数据，先获取
    if (allGuestsData.value.length === 0) {
      await getAllGuestsData();
    }

    // 显示确认弹框
    const confirmResult = await ElMessageBox.confirm(
      '确定要导出所有表格数据到 Excel 文件吗？',
      '提示框',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    if (confirmResult === 'confirm') {
      // 获取表格数据
      const headers = ['ID', '客人姓名',  '电话号码', '身份证号', '入住房间', '入住时间', '退房时间'];
      const data = [headers].concat(allGuestsData.value.map(row => [
        row.id,
        row.name,
        row.phone_number,
        row.id_number,
        row.number,
        row.check_in_date,
        row.check_out_date
      ]));

      // 创建工作簿
      const worksheet = XLSX.utils.aoa_to_sheet(data);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      // 保存 Excel 文件
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
      saveAs(new Blob([excelBuffer], { type: 'application/octet-stream' }), 'guests_data.xlsx');

      ElMessage({
        type: 'success',
        message: '导出成功'
      });
    }
  } catch (error) {
    console.error('Error exporting data:', error);
  } finally {
    exportButtonLoading.value = false;
  }
};

</script>

<template>
  <el-input v-model="checkObj.name" style="width: 150px" placeholder="请输入查询的客人姓名" clearable/>
  <el-input v-model="checkObj.phone_number" style="width: 150px" placeholder="请输入查询的电话号码" clearable/>
  <el-button type="success" @click="checkDate">查询</el-button>

  <el-button type="primary" @click="exportTableToExcel" :loading="exportButtonLoading">
  <el-icon><Download /></el-icon>
   下载Excel
</el-button>

  <el-table :data="tableData" style="width: 100%">
    <!-- <el-table-column prop="id" label="ID" width="180" /> -->
    <el-table-column prop="name" label="客人姓名" width="180" />
    <el-table-column prop="phone_number" label="电话号码" width="180" />
    <el-table-column prop="id_number" label="身份证号" width="180" />
    <el-table-column prop="number" label="入住房间" width="180" />
    <el-table-column prop="check_in_date" label="入住时间" width="180" />
    <el-table-column prop="check_out_date" label="退房时间" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="danger" @click="del(scope.$index,scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    :page-size="checkObj.size"
    :current-page="checkObj.page"
    background
    layout="prev, pager, next"
    :total="total"
    @current-change="checkDate"
  />
  <!-- 新增信息弹出框 -->
  <el-dialog v-model="addWinVisible" title="信息登记" width="500">
    <el-form :model="addObject">
      <el-form-item label="客人姓名" label-width="80">
        <el-input v-model="addObject.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="电话号码" label-width="80">
        <el-input v-model="addObject.phone_number" autocomplete="off" />
      </el-form-item>
      <el-form-item label="身份证号" label-width="80">
        <el-input v-model="addObject.id_number" autocomplete="off" />
      </el-form-item>
      <el-form-item label="入住时间" label-width="80">
        <el-input v-model="addObject.check_in_date" autocomplete="off" />
      </el-form-item>
      <el-form-item label="退房时间" label-width="80">
        <el-input v-model="addObject.check_out_date" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addWinVisible = false">取消</el-button>
        <el-button type="primary" @click="addSave">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 编辑信息弹出框 -->
  <el-dialog v-model="editWinVisible" title="修改入住信息" width="500">
    <el-form :model="editObject">
      <el-form-item label="电话号码" label-width="80">
        <el-input v-model="editObject.phone_number" autocomplete="off" />
      </el-form-item>
      <el-form-item label="退房时间" label-width="80">
        <el-input v-model="editObject.check_out_date" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editWinVisible = false">取消</el-button>
        <el-button type="primary" @click="editSave">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>


<style>
</style>
